In [0]:
#!wget https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/dogImages.zip
#!wget https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/lfw.zip
In [0]:
#!unzip dogImages.zip
#!unzip lfw.zip

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.

  • Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [3]:
import numpy as np
from glob import glob

# load filenames for human and dog images
human_files = np.array(glob("/content/lfw/*/*"))
dog_files = np.array(glob("/content/dogImages/*/*/*"))

# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
#print(dog_files[0])
There are 13233 total human images.
There are 8351 total dog images.

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [8]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('/content/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[1])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [0]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: (You can print out your results and/or write your percentages in this cell)

In [6]:
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
total_human=0
for i in range(len(human_files_short)):
  a=face_detector(human_files_short[i])
  if(a == True):
    total_human +=1
print("Human Images Detected with a Face : ",(total_human/len(human_files_short))*100)

total_dog=0
for i in range(len(dog_files_short)):
  d=face_detector(dog_files_short[i])
  if(d == True):
    total_dog +=1
print("Dog images detected with the face : ",(total_dog/len(dog_files_short))*100)
Human Images Detected with a Face :  99.0
Dog images detected with the face :  7.000000000000001

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [0]:
!pip install mtcnn
Collecting mtcnn
  Downloading https://files.pythonhosted.org/packages/67/43/abee91792797c609c1bf30f1112117f7a87a713ebaa6ec5201d5555a73ef/mtcnn-0.1.0-py3-none-any.whl (2.3MB)
     |████████████████████████████████| 2.3MB 3.5MB/s 
Requirement already satisfied: keras>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from mtcnn) (2.3.1)
Requirement already satisfied: opencv-python>=4.1.0 in /usr/local/lib/python3.6/dist-packages (from mtcnn) (4.1.2.30)
Requirement already satisfied: scipy>=0.14 in /usr/local/lib/python3.6/dist-packages (from keras>=2.0.0->mtcnn) (1.4.1)
Requirement already satisfied: numpy>=1.9.1 in /usr/local/lib/python3.6/dist-packages (from keras>=2.0.0->mtcnn) (1.18.4)
Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras>=2.0.0->mtcnn) (2.10.0)
Requirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.6/dist-packages (from keras>=2.0.0->mtcnn) (1.0.8)
Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.6/dist-packages (from keras>=2.0.0->mtcnn) (1.12.0)
Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from keras>=2.0.0->mtcnn) (1.1.2)
Requirement already satisfied: pyyaml in /usr/local/lib/python3.6/dist-packages (from keras>=2.0.0->mtcnn) (3.13)
Installing collected packages: mtcnn
Successfully installed mtcnn-0.1.0
In [0]:
from matplotlib import pyplot
from matplotlib.patches import Rectangle
from mtcnn.mtcnn import MTCNN
 
# draw an image with detected objects
def Face_detector_with_boxes(filename, result_list):
	# load the image
	data = pyplot.imread(filename)
	# plot the image
	pyplot.imshow(data)
	# get the context for drawing boxes
	ax = pyplot.gca()
	# plot each box
	for result in result_list:
		# get coordinates
		x, y, width, height = result['box']
		# create the shape
		rect = Rectangle((x, y), width, height, fill=False, color='red')
		# draw the box
		ax.add_patch(rect)
	# show the plot
	pyplot.show()
# returns "True" if face is detected in image stored at img_path
def face_detector_deep(img_path):
    filename = img_path
    # load image from file
    pixels = pyplot.imread(filename)
    # create the detector, using default weights
    detector = MTCNN()
    # detect faces in the image
    faces = detector.detect_faces(pixels)
    #print(len(faces))
    # display faces on the original image
    #Face_detector_with_boxes(filename, faces)
    return len(faces) > 0
Using TensorFlow backend.
In [0]:
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
total_human=0
for i in range(len(human_files_short)):
  a=face_detector_deep(human_files_short[i])
  if(a == True):
    total_human +=1
print("Human Images Detected with a Face : ",(total_human/len(human_files_short))*100)

total_dog=0
for i in range(len(dog_files_short)):
  d=face_detector_deep(dog_files_short[i])
  if(d == True):
    total_dog +=1
print("Dog images detected with the face : ",(total_dog/len(dog_files_short))*100)
Human Images Detected with a Face :  100.0
Dog images detected with the face :  16.0

Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [10]:
import torch
import torchvision.models as models

# define VGG16 model
VGG16 = models.vgg16(pretrained=True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()

# move model to GPU if CUDA is available
if use_cuda:
    VGG16 = VGG16.cuda()
#print(VGG16)
Downloading: "https://download.pytorch.org/models/vgg16-397923af.pth" to /root/.cache/torch/checkpoints/vgg16-397923af.pth

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

In [11]:
from PIL import Image
import torchvision.transforms as transforms

def Load_Pre_Process_Image(path):
    img = Image.open(path)#.convert('RGB')
    #img = asarray(img)
    transform = transforms.Compose([transforms.Resize(size=(256,256)),
                                    transforms.CenterCrop(224),
                                    transforms.ToTensor(),
                                    transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]
                                                         )])
    img_t = transform(img)
    #print(img_t.shape)
    batch_t = torch.unsqueeze(img_t,0)
    #print(batch_t.shape)
    return batch_t


def VGG16_predict(img_path):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    #print("In")
    ## TODO: Complete the function.
    pre_processed_image = Load_Pre_Process_Image(img_path)
    if torch.cuda.is_available():
      pre_processed_image = pre_processed_image.cuda()

    out = VGG16(pre_processed_image)
    #print(out.shape)
    _, pred = torch.max(out, 1)
    #print(pred.item())
    index = pred.item()
    return index

VGG16_predict(dog_files[0])
Out[11]:
164

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [12]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    ## TODO: Complete the function.
    index = VGG16_predict(img_path)
    #print(index)
    dog= False
    X=151
    Y=268
    if X <= index <= Y:
    #if index not in range(151, 268):
    #if (index >= 151 and index<=268):
      dog=True

    return dog # true/false
#for i in range(len(dog_files)):
#  dog_detector(dog_files[i])
dog_detector(dog_files[0])
Out[12]:
True

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [0]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
total_human=0
for i in range(len(human_files_short)):
  a=dog_detector(human_files_short[i])
  if(a == True):
    total_human +=1
print("Human Images Detected with a Face : ",(total_human/len(human_files_short))*100)

total_dog=0
for i in range(len(dog_files_short)):
  d=dog_detector(dog_files_short[i])
  if(d == True):
    total_dog +=1
print("Dog images detected with the face : ",(total_dog/len(dog_files_short))*100)
Human Images Detected with a Face :  0.0
Dog images detected with the face :  96.0

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [0]:
### (Optional) 
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [0]:
import os
### TODO: Write data loaders for training, validation, and test sets
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision import datasets, transforms

data_dir = '/content/dogImages/'
train_dir = "./dogImages/train"
valid_dir = "./dogImages/valid"
test_dir = "./dogImages/test"

normalize = transforms.Normalize(
   mean=[0.485, 0.456, 0.406],
   std=[0.229, 0.224, 0.225]
)

batch_size=22
#num_workers=2
# TODO: Define transforms for the training data and testing data
data_transforms = {
    'train':transforms.Compose([transforms.RandomRotation(30),
                                       transforms.Resize(256),
                                       transforms.RandomResizedCrop(224),
                                       transforms.RandomVerticalFlip(),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ColorJitter(brightness=0.2, hue=.1, saturation=.1),
                                       transforms.ToTensor(),
                                       normalize]) ,
              'valid':transforms.Compose([transforms.RandomRotation(30),
                                       transforms.Resize(256),
                                       transforms.RandomVerticalFlip(),
                                       transforms.RandomResizedCrop(224),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ToTensor(),
                                       normalize]) ,
              'test':transforms.Compose([transforms.Resize(255),
                                      transforms.CenterCrop(224),
                                      transforms.ToTensor(),
                                      normalize])
}


dirs = {'train': train_dir, 
        'valid': valid_dir,
        'test': test_dir}


datasets = {x: torchvision.datasets.ImageFolder(dirs[x], transform=data_transforms[x]) for x in ['train', 'valid', 'test']}

dataloaders = {x: torch.utils.data.DataLoader(datasets[x], batch_size=22, shuffle=True, num_workers=0) for x in ['train', 'valid','test']}

dataset_sizes = {x: len(datasets[x]) for x in ['train', 'valid','test']}
print(dataset_sizes)
#print(len(dataloaders['train']))
{'train': 6680, 'valid': 835, 'test': 836}

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?

Answer:
1- Having slightly larger source images is useful for doing basic data augmentation according to me it will work fine. For example, we can train our CNN by taking several random 224x224 crops from the same 256x256 image. 2- I don't know about it much but according to the mentor if we use we will get better results so i have used transforms.RandomRotation(30) and transforms.RandomHorizontalFlip().

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

In [0]:
import torch.nn as nn
import torch.nn.functional as F

# define the CNN architecture
class Net(nn.Module):
    ### TODO: choose an architecture, and complete the class
    def __init__(self):
        super(Net, self).__init__()
        ## Define layers of a CNN
        self.conv1_1 = nn.Conv2d(3 , 32 , 3 , stride = 2 , padding=1)
        self.conv1_2 = nn.Conv2d(32 , 64 , 3 , stride = 2 , padding=1)
        self.conv1_3 = nn.Conv2d(64 , 128 , 3 , padding=1)
        # max pooling layer
        self.pool = nn.MaxPool2d(2,2)

        # linear layer (64 * 4 * 4 -> 500)
        self.fc1 = nn.Linear(128 * 7 * 7, 500)
        self.fc2 = nn.Linear(500, 133)
        
        # dropout layer (p=0.3)
        self.dropout = nn.Dropout(0.3)

    def forward(self, x):
        ## Define forward behavior
        x = F.relu(self.conv1_1(x))
        x = self.pool(x)
        x = F.relu(self.conv1_2(x))
        x = self.pool(x)
        x = F.relu(self.conv1_3(x))
        x = self.pool(x)
       
        #print(x.shape)

        # flatten image input
        x = x.view(x.size(0), 128 * 7 * 7)
        #print(x.shape)

        # add dropout layer
        x = self.dropout(x)

        # add 1st hidden layer, with relu activation function
        x = F.relu(self.fc1(x))
        # add dropout layer
        x = self.dropout(x)
        # add 2nd hidden layer, with relu activation function
        x = self.fc2(x)
        #x = F.log_softmax(self.fc2(x), dim=1)

        return x

#-#-# You do NOT have to modify the code below this line. #-#-#

# instantiate the CNN
model_scratch = Net()
# check if CUDA is available
use_cuda = torch.cuda.is_available()
# move tensors to GPU if CUDA is available
if use_cuda:
    model_scratch.cuda()
print(model_scratch)
Net(
  (conv1_1): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
  (conv1_2): Conv2d(32, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
  (conv1_3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (fc1): Linear(in_features=6272, out_features=500, bias=True)
  (fc2): Linear(in_features=500, out_features=133, bias=True)
  (dropout): Dropout(p=0.3, inplace=False)
)

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

__Answer:__

  • I have taken this arhitecture and kept it simple because the more cnn and fc i add it was overfitting and giving me only 1% - 2%.
  • But than I decided to decrease fc layers to 2 and 3 cnn layers so that patters are recognized.
  • Here i have started with conv1_1 with 3 to 32 so that more patterns and colurs everyting is decided.
  • And than taken con1_2 & con1_3 same with kernel 3 and stride 2.And taken a dropout of 30%.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [0]:
import torch.optim as optim

### TODO: select loss function
criterion_scratch = nn.CrossEntropyLoss()

### TODO: select optimizer
optimizer_scratch = optim.SGD(model_scratch.parameters() , lr=0.1)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [0]:
# the following import is required for training to be robust to truncated images
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import numpy as np

train_losses, valid_losses = [], []
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path,last_validation_loss=None):
    """returns trained model"""
    # initialize tracker for minimum validation loss
    if last_validation_loss is not None:
        valid_loss_min = last_validation_loss
    else:
      # initialize tracker for minimum validation loss
      valid_loss_min = np.Inf 
    
    for epoch in range(1, n_epochs+1):
        # initialize variables to monitor training and validation loss
        train_loss = 0.0
        valid_loss = 0.0
        
        ###################
        # train the model #
        ###################
        model.train()
        for batch_idx, (data, target) in enumerate(loaders['train']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## find the loss and update the model parameters accordingly
            optimizer.zero_grad()
            output = model(data)
            loss = criterion(output,target)
            loss.backward()
            optimizer.step()
            train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
            #if batch_idx % 100 == 0:
                #print('Epoch %d, Batch %d loss: %.6f' % (epoch, batch_idx + 1, train_loss))
            #train_loss += loss.item()*data.size(0)
            ## record the average training loss, using something like
            
        ######################    
        # validate the model #
        ######################
        model.eval()
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## update the average validation loss
            output = model(data)
            loss = criterion(output,target)
            valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
            #valid_losses.append(valid_loss.item())

        train_losses.append(train_loss/len(loaders['train'].dataset))
        valid_losses.append(valid_loss/len(loaders['valid'].dataset))
        # print training/validation statistics 
        print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(epoch, train_loss,valid_loss))
        
        ## TODO: save the model if validation loss has decreased
        if valid_loss <= valid_loss_min:
          print("Validation Loss decreased ({:.6f} --> {:.6f}). Saving Model ...".format(
              valid_loss_min,
              valid_loss
          ))
          torch.save(model.state_dict(),save_path)
          valid_loss_min = valid_loss
            
    # return trained model
    return model
In [0]:
# train the model
model_scratch = train(35, dataloaders, model_scratch, optimizer_scratch, criterion_scratch, use_cuda, 'model_scratch.pt')
Epoch: 1 	Training Loss: 4.707118 	Validation Loss: 4.644185
Validation Loss decreased (inf --> 4.644185). Saving Model ...
Epoch: 2 	Training Loss: 4.659263 	Validation Loss: 4.644209
Epoch: 3 	Training Loss: 4.627527 	Validation Loss: 4.485571
Validation Loss decreased (4.644185 --> 4.485571). Saving Model ...
Epoch: 4 	Training Loss: 4.580379 	Validation Loss: 4.424811
Validation Loss decreased (4.485571 --> 4.424811). Saving Model ...
Epoch: 5 	Training Loss: 4.536822 	Validation Loss: 4.519120
Epoch: 6 	Training Loss: 4.487391 	Validation Loss: 4.328768
Validation Loss decreased (4.424811 --> 4.328768). Saving Model ...
Epoch: 7 	Training Loss: 4.460126 	Validation Loss: 4.248219
Validation Loss decreased (4.328768 --> 4.248219). Saving Model ...
Epoch: 8 	Training Loss: 4.416750 	Validation Loss: 4.310830
Epoch: 9 	Training Loss: 4.390832 	Validation Loss: 4.174593
Validation Loss decreased (4.248219 --> 4.174593). Saving Model ...
Epoch: 10 	Training Loss: 4.366272 	Validation Loss: 4.199836
Epoch: 11 	Training Loss: 4.357217 	Validation Loss: 4.156607
Validation Loss decreased (4.174593 --> 4.156607). Saving Model ...
Epoch: 12 	Training Loss: 4.319546 	Validation Loss: 4.166471
Epoch: 13 	Training Loss: 4.287812 	Validation Loss: 4.153191
Validation Loss decreased (4.156607 --> 4.153191). Saving Model ...
Epoch: 14 	Training Loss: 4.275107 	Validation Loss: 4.297792
Epoch: 15 	Training Loss: 4.251595 	Validation Loss: 4.095507
Validation Loss decreased (4.153191 --> 4.095507). Saving Model ...
Epoch: 16 	Training Loss: 4.251182 	Validation Loss: 4.083657
Validation Loss decreased (4.095507 --> 4.083657). Saving Model ...
Epoch: 17 	Training Loss: 4.213929 	Validation Loss: 3.986978
Validation Loss decreased (4.083657 --> 3.986978). Saving Model ...
Epoch: 18 	Training Loss: 4.210449 	Validation Loss: 4.044538
Epoch: 19 	Training Loss: 4.193941 	Validation Loss: 4.050226
Epoch: 20 	Training Loss: 4.151542 	Validation Loss: 3.941729
Validation Loss decreased (3.986978 --> 3.941729). Saving Model ...
Epoch: 21 	Training Loss: 4.138469 	Validation Loss: 3.897166
Validation Loss decreased (3.941729 --> 3.897166). Saving Model ...
Epoch: 22 	Training Loss: 4.132205 	Validation Loss: 4.069100
Epoch: 23 	Training Loss: 4.119895 	Validation Loss: 3.827726
Validation Loss decreased (3.897166 --> 3.827726). Saving Model ...
Epoch: 24 	Training Loss: 4.101130 	Validation Loss: 3.848114
Epoch: 25 	Training Loss: 4.084881 	Validation Loss: 3.866724
Epoch: 26 	Training Loss: 4.098966 	Validation Loss: 3.719445
Validation Loss decreased (3.827726 --> 3.719445). Saving Model ...
Epoch: 27 	Training Loss: 4.039870 	Validation Loss: 3.990257
Epoch: 28 	Training Loss: 4.048073 	Validation Loss: 3.741148
Epoch: 29 	Training Loss: 4.056621 	Validation Loss: 3.981274
Epoch: 30 	Training Loss: 3.999363 	Validation Loss: 3.812988
Epoch: 31 	Training Loss: 4.018620 	Validation Loss: 3.795890
Epoch: 32 	Training Loss: 3.976574 	Validation Loss: 3.829351
Epoch: 33 	Training Loss: 4.017912 	Validation Loss: 3.781225
Epoch: 34 	Training Loss: 3.994215 	Validation Loss: 3.660203
Validation Loss decreased (3.719445 --> 3.660203). Saving Model ...
Epoch: 35 	Training Loss: 3.976481 	Validation Loss: 3.745751
In [0]:
# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
Out[0]:
<All keys matched successfully>

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [0]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        # move to GPU
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        # calculate the loss
        loss = criterion(output, target)
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        # compare predictions to true label
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))

# call test function    
test(dataloaders, model_scratch, criterion_scratch, use_cuda)
Test Loss: 3.636117


Test Accuracy: 14% (122/836)
In [0]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt

plt.plot(train_losses, label='Training loss')
plt.plot(valid_losses, label='Validation loss')
plt.legend(frameon=False)
Out[0]:
<matplotlib.legend.Legend at 0x7f32c4b9e400>

Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [0]:
import os
### TODO: Write data loaders for training, validation, and test sets
import matplotlib.pyplot as plt
import torch
from torchvision import datasets, transforms

data_dir = '/content/dogImages/'
train_dir = "./dogImages/train"
valid_dir = "./dogImages/valid"
test_dir = "./dogImages/test"

normalize = transforms.Normalize(
   mean=[0.485, 0.456, 0.406],
   std=[0.229, 0.224, 0.225]
)

batch_size=22
#num_workers=2
# TODO: Define transforms for the training data and testing data
transforms = {
    'train':transforms.Compose([transforms.RandomRotation(30),
                                       transforms.Resize(256),
                                       transforms.RandomResizedCrop(224),
                                       transforms.RandomVerticalFlip(),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ColorJitter(brightness=0.2, hue=.1, saturation=.1),
                                       transforms.ToTensor(),
                                       normalize]) ,
              'valid':transforms.Compose([transforms.RandomRotation(30),
                                       transforms.Resize(256),
                                       transforms.RandomVerticalFlip(),
                                       transforms.RandomResizedCrop(224),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ToTensor(),
                                       normalize]) ,
              'test':transforms.Compose([transforms.Resize(255),
                                      transforms.CenterCrop(224),
                                      transforms.ToTensor(),
                                      normalize])
}


dirs = {'train': train_dir, 
        'valid': valid_dir,
        'test': test_dir}


datasets = {x: torchvision.datasets.ImageFolder(dirs[x], transform=data_transforms[x]) for x in ['train', 'valid', 'test']}

dataloaders = {x: torch.utils.data.DataLoader(datasets[x], batch_size=22, shuffle=True, num_workers=0) for x in ['train', 'valid','test']}

dataset_sizes = {x: len(datasets[x]) for x in ['train', 'valid','test']}
print(dataset_sizes)
print(len(dataloaders['train']))
{'train': 6680, 'valid': 835, 'test': 836}
304

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

In [0]:
model_transfer = models.vgg19(pretrained=True)
print(model_transfer)
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace=True)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace=True)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace=True)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace=True)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace=True)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace=True)
    (16): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (17): ReLU(inplace=True)
    (18): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (19): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace=True)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace=True)
    (23): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (24): ReLU(inplace=True)
    (25): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (26): ReLU(inplace=True)
    (27): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace=True)
    (30): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (31): ReLU(inplace=True)
    (32): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (33): ReLU(inplace=True)
    (34): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (35): ReLU(inplace=True)
    (36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace=True)
    (2): Dropout(p=0.5, inplace=False)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace=True)
    (5): Dropout(p=0.5, inplace=False)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)
In [0]:
import torchvision.models as models
import torch.nn as nn

## TODO: Specify model architecture 
print(model_transfer.classifier[6].in_features) 
print(model_transfer.classifier[6].out_features) 
classes = 133

# Freeze training for all "features" layers
for param in model_transfer.features.parameters():
    param.requires_grad = False
n_input = model_transfer.classifier[6].in_features
last_layer = nn.Linear(n_input ,133)
model_transfer.classifier[6] = last_layer

print(model_transfer)

if use_cuda:
    model_transfer = model_transfer.cuda()
4096
1000
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace=True)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace=True)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace=True)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace=True)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace=True)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace=True)
    (16): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (17): ReLU(inplace=True)
    (18): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (19): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace=True)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace=True)
    (23): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (24): ReLU(inplace=True)
    (25): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (26): ReLU(inplace=True)
    (27): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace=True)
    (30): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (31): ReLU(inplace=True)
    (32): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (33): ReLU(inplace=True)
    (34): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (35): ReLU(inplace=True)
    (36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace=True)
    (2): Dropout(p=0.5, inplace=False)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace=True)
    (5): Dropout(p=0.5, inplace=False)
    (6): Linear(in_features=4096, out_features=133, bias=True)
  )
)

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

  • I have taken Vgg19 rather than Vgg16 because it is deeper thna it. Though it is not winner model but good even in could use resnet50 but it is deep and will take more time to train.
  • I have choosed because of it's Simpplicity which is using only 3×3 convolutional layers stacked on top of each other in increasing depth.
  • Reducing volume size is handled by max pooling. Two fully-connected layers, each with 4,096 nodes are then followed by a CrossEntropy classifier.
  • As we have to use transfer learning I think it is the best model as it take less time to train in gpu though it has drawbacks as well.(i.e model size is > 500 MB)
  • If these model doesn't work than i would have choose resnet50 because it's size is only 104 Mb but it will take more time to train.link
  • And we have to only train the FC layers to get the output so i have changed the fc layer 6 with output as 133 because by deafult it was 1000.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [0]:
import torch.optim as optim

criterion_transfer = nn.CrossEntropyLoss()
optimizer_transfer = optim.SGD(model_transfer.classifier.parameters(), lr=0.01)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

In [0]:
# train the model
model_transfer = train(35, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')

# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
Epoch: 1 	Training Loss: 3.136308 	Validation Loss: 1.946918
Validation Loss decreased (inf --> 1.946918). Saving Model ...
Epoch: 2 	Training Loss: 2.167969 	Validation Loss: 1.698405
Validation Loss decreased (1.946918 --> 1.698405). Saving Model ...
Epoch: 3 	Training Loss: 1.964087 	Validation Loss: 1.598018
Validation Loss decreased (1.698405 --> 1.598018). Saving Model ...
Epoch: 4 	Training Loss: 1.840833 	Validation Loss: 1.553071
Validation Loss decreased (1.598018 --> 1.553071). Saving Model ...
Epoch: 5 	Training Loss: 1.815225 	Validation Loss: 1.502471
Validation Loss decreased (1.553071 --> 1.502471). Saving Model ...
Epoch: 6 	Training Loss: 1.729863 	Validation Loss: 1.546634
Epoch: 7 	Training Loss: 1.678857 	Validation Loss: 1.478498
Validation Loss decreased (1.502471 --> 1.478498). Saving Model ...
Epoch: 8 	Training Loss: 1.675364 	Validation Loss: 1.463195
Validation Loss decreased (1.478498 --> 1.463195). Saving Model ...
Epoch: 9 	Training Loss: 1.588232 	Validation Loss: 1.476871
Epoch: 10 	Training Loss: 1.597029 	Validation Loss: 1.430949
Validation Loss decreased (1.463195 --> 1.430949). Saving Model ...
Epoch: 11 	Training Loss: 1.560688 	Validation Loss: 1.567885
Epoch: 12 	Training Loss: 1.573389 	Validation Loss: 1.525819
Epoch: 13 	Training Loss: 1.534455 	Validation Loss: 1.563508
Epoch: 14 	Training Loss: 1.493418 	Validation Loss: 1.460158
Epoch: 15 	Training Loss: 1.502045 	Validation Loss: 1.431467
Epoch: 16 	Training Loss: 1.486428 	Validation Loss: 1.432783
Epoch: 17 	Training Loss: 1.441760 	Validation Loss: 1.503613
Epoch: 18 	Training Loss: 1.431509 	Validation Loss: 1.417381
Validation Loss decreased (1.430949 --> 1.417381). Saving Model ...
Epoch: 19 	Training Loss: 1.403938 	Validation Loss: 1.418741
Epoch: 20 	Training Loss: 1.386498 	Validation Loss: 1.414864
Validation Loss decreased (1.417381 --> 1.414864). Saving Model ...
Epoch: 21 	Training Loss: 1.390158 	Validation Loss: 1.434399
Epoch: 22 	Training Loss: 1.375515 	Validation Loss: 1.392524
Validation Loss decreased (1.414864 --> 1.392524). Saving Model ...
Epoch: 23 	Training Loss: 1.372107 	Validation Loss: 1.421616
Epoch: 24 	Training Loss: 1.352561 	Validation Loss: 1.340111
Validation Loss decreased (1.392524 --> 1.340111). Saving Model ...
Epoch: 25 	Training Loss: 1.349072 	Validation Loss: 1.460524
Epoch: 26 	Training Loss: 1.312223 	Validation Loss: 1.466098
Epoch: 27 	Training Loss: 1.302848 	Validation Loss: 1.426642
Epoch: 28 	Training Loss: 1.276533 	Validation Loss: 1.360532
Epoch: 29 	Training Loss: 1.305286 	Validation Loss: 1.479566
Epoch: 30 	Training Loss: 1.271388 	Validation Loss: 1.390806
Epoch: 31 	Training Loss: 1.266157 	Validation Loss: 1.334272
Validation Loss decreased (1.340111 --> 1.334272). Saving Model ...
Epoch: 32 	Training Loss: 1.300015 	Validation Loss: 1.383210
Epoch: 33 	Training Loss: 1.243307 	Validation Loss: 1.360920
Epoch: 34 	Training Loss: 1.281405 	Validation Loss: 1.410604
Epoch: 35 	Training Loss: 1.249939 	Validation Loss: 1.364092
Out[0]:
<All keys matched successfully>
In [0]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        # move to GPU
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        # calculate the loss
        loss = criterion(output, target)
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        # compare predictions to true label
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))
In [0]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt

plt.plot(train_losses, label='Training loss')
plt.plot(valid_losses, label='Validation loss')
plt.legend(frameon=False)
Out[0]:
<matplotlib.legend.Legend at 0x7f0486073a58>

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [0]:
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
Test Loss: 0.486777


Test Accuracy: 85% (715/836)

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [0]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

# list of class names by index, i.e. a name can be accessed like class_names[0]
class_names = [item[4:].replace("_", " ") for item in dataloaders['train'].dataset.classes]

from PIL import Image
import torchvision.transforms as transforms

def Load_Pre_Process_Image(path):
    img = Image.open(path).convert('RGB')
    #img = asarray(img)
    transform = transforms.Compose([transforms.Resize(size=(256,256)),
                                    transforms.CenterCrop(224),
                                    transforms.ToTensor(),
                                    transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]
                                                         )])
    img_t = transform(img)
    #print(img_t.shape)
    batch_t = torch.unsqueeze(img_t,0)
    #print(batch_t.shape)
    return batch_t



def predict_breed_transfer(img_path):
    # load the image and return the predicted breed
    pre_processed_image = Load_Pre_Process_Image(img_path)
    if torch.cuda.is_available():
      pre_processed_image = pre_processed_image.cuda()

    out = model_transfer(pre_processed_image)
    #print(out.shape)
    _, pred = torch.max(out, 1)
    #print(pred.item())
    index = pred.item()
    #print(class_names[index])
    predicted_result = class_names[index]

    return predicted_result
In [0]:
predict_breed_transfer(dog_files[0])
Out[0]:
'Anatolian shepherd dog'

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [0]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def run_app(img_path):
    image = Image.open(img_path)
    plt.imshow(image)
    plt.show()
    ## handle cases for a human face, dog, and neither
    if(dog_detector(img_path) == True):
      dog_result = predict_breed_transfer(img_path)
      print("Dog is detected \nIt looks like : {}".format(dog_result))
    elif(face_detector(img_path) == True):
      human_dog_result = predict_breed_transfer(img_path)
      print("Human is Detected \nIf you were a dog you will look like {}".format(human_dog_result))
    else:
      print("Oops I think I Dectected Nothing :( ")
In [0]:
for img_file in os.listdir('./dogImages/test/036.Briard'):
    img_path = os.path.join('./dogImages/test/036.Briard', img_file)
    run_app(img_path)
Dog is detected 
It looks like : Briard
Dog is detected 
It looks like : Briard
Dog is detected 
It looks like : Briard
Dog is detected 
It looks like : Briard
Dog is detected 
It looks like : Briard
Dog is detected 
It looks like : Briard
Dog is detected 
It looks like : Briard
Dog is detected 
It looks like : Briard

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: (Three possible points for improvement)

  • I think image should be preprosed more like removing the un-necessary background it is hard but the result accuracy will increase due to that.
  • It has done more than what i expected using the Vgg19 model because most of the results are right.But there is always room for improvement.
  • And it has worked for image of cat as well i have given the cat image and it has given error for that which i am happy. So i think the model is pretty good and meets my expectaions ^_^.
In [0]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
image_dog = ['./dogImages/test/124.Poodle/Poodle_07910.jpg','./dogImages/test/039.Bull_terrier/Bull_terrier_02750.jpg','./dogImages/test/059.Doberman_pinscher/Doberman_pinscher_04190.jpg'] 
## suggested code, below
image_human = ['./lfw/Ben_Kingsley/Ben_Kingsley_0001.jpg','./lfw/Keanu_Reeves/Keanu_Reeves_0007.jpg','./lfw/Angelina_Jolie/Angelina_Jolie_0018.jpg']
for file in np.hstack((image_human[:3], image_dog[:3])):
    run_app(file)
Human is Detected 
If you were a dog you will look like Bloodhound
Human is Detected 
If you were a dog you will look like Bullmastiff
Human is Detected 
If you were a dog you will look like Dogue de bordeaux
Dog is detected 
It looks like : Poodle
Dog is detected 
It looks like : Bull terrier
Dog is detected 
It looks like : Doberman pinscher
In [0]:
run_app('/content/simu.jpg')
run_app('/content/paj.jpeg')
run_app('/content/Siamese-Cat.jpg')
Human is Detected 
If you were a dog you will look like German pinscher
Human is Detected 
If you were a dog you will look like Silky terrier
Oops I think I Dectected Nothing :(